package com.bo.startup;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.log4j.Logger;

import com.bo.exception.WeiboException;
import com.bo.gather.GatherService;
import com.bo.gather.bean.GatherBean;
import com.bo.gather.bean.weibo.WeiboRuleBean;
import com.bo.gather.data.SearchRepeatData;
import com.bo.sina.weibo.access.AccessInfo;
import com.bo.sina.weibo.access.AccessToken;
import com.bo.sina.weibo.share.ShareManager;
import com.bo.weibo.WeiboService;
import com.bo.weibo.bean.SendDataInfo;
import com.bo.weibo.bean.WeiboSendBean;
import com.portal.framework.util.DateTimeUtil;

public class Task extends Thread{
	static Logger log = Logger.getLogger(Task.class.getName());
	private GatherBean gatherbean;
	
	
	public GatherBean getGatherbean() {
		return gatherbean;
	}
	public void setGatherbean(GatherBean gatherbean) {
		this.gatherbean = gatherbean;
	}
	
	
	/**
	 * 1.	开关设置存储在规则文件中weibo.switch=on/off
			线程执行时，监听weibo.switch是否开启，on才能执行，监控时间根据weibo.random.all来计算。
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 20条内容发布，每条内容设定睡眠时间，
		10个微博账号 *20个时间 升序排序
		while（true）{
		for(10个账号){
			while(每个账号的20个时间){
				if(账号时间<当前时间){
					发送微博+去除内容
				else{
					break;
		}
		Thread.sheep(1000*10)//10秒钟来一次
	 */
	public void run() {
		
		while(true){
			WeiboRuleBean weiboRuleBean= this.gatherbean.getWeiboRuleBean();
			if(weiboRuleBean==null){
				return ;
			}
			if(WeiboException.isLoginException()|| WeiboException.isShareException()){
				log.error("微博出异常："+WeiboException.toInfo());
				return ;
			}
			if("on".equals(weiboRuleBean.getIsswitch())){
				//计算采集内容
				GatherService gatherService =new GatherService();
//				if(gatherbean.getParentUrl()!=null && gatherbean.getParentUrl().length>0){
//					for(String url:gatherbean.getParentUrl()){
//						List<Map<String,String>> gatherList=gatherService.calculateSigleGather(gatherbean, url);
//					}
//				}
				
				List<Map<String,String>> gatherList= gatherService.calculateGather(gatherbean);
				
				if(gatherList!=null){
					//计算发送微博的内容
					WeiboService weiboService=new WeiboService();
					List<SendDataInfo> sendDataList=weiboService.calculateSendData(gatherList, weiboRuleBean,this.gatherbean.getOnlyid());
					if(sendDataList!=null){
						//计算本线程要发送哪些微博用户
						List<WeiboSendBean> weibolist=this.calculateSendUser(weiboRuleBean);
						
						//判断是相同发送还是不同发送
						if("different".equals(weiboRuleBean.getUserRule())){
							this.executeDifferent(weibolist,weiboRuleBean.getRandom(), sendDataList);
						}else if("same".equals(weiboRuleBean.getUserRule())){
							this.executeSame(weibolist, weiboRuleBean.getRandom(), sendDataList);
						}
						//过滤重复后 设置等待时间
						for(WeiboSendBean weibo:weibolist){
							log.info(weibo.getAccessInfo().getNick()+"  分配到"+weibo.getSendDataList().size()+"条数据");
							SearchRepeatData srd=new SearchRepeatData();
							srd.cleanRepeatData(weibo);
							log.info(weibo.getAccessInfo().getNick()+"  过滤剩下"+weibo.getSendDataList().size()+"条数据");
							
							//设置间隔时间
							Date nowdate=new Date();
							long datetime=nowdate.getTime();
							for(SendDataInfo senddatainfo:weibo.getSendDataList()){
								int random=this.getRandom(weiboRuleBean.getRandom()[0], weiboRuleBean.getRandom()[1]);
								datetime=datetime+1000L*60*random;
								senddatainfo.setDatetime(datetime);
							}
						}
						
						for(WeiboSendBean weibo:weibolist){
//							log.info(weibo.getScreenName()+"  过滤剩下"+weibo.getSendDataList().size()+"条数据 分别如下");
							for(SendDataInfo senddatainfo:weibo.getSendDataList()){
								Date date=new Date();
								date.setTime(senddatainfo.getDatetime());
								try {
									String s=java.net.URLDecoder.decode(senddatainfo.getContent(), "utf-8");
									log.info(weibo.getAccessInfo().getNick()+"---"+DateTimeUtil.formatDateTime(date)+"---"+s);
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								
							}
						}
						
						//进入死循环检查
						while(true){
							if(WeiboException.isLoginException()|| WeiboException.isShareException()){
								log.error("微博出异常："+WeiboException.toInfo());
								return ;
							}
							if("off".equals(weiboRuleBean.getIsswitch())){
								log.info("监控到《"+gatherbean.getTitle()+"》的状态为OFF，临时退出");
								break;
							}
							Date d = new Date();
							int hours = d.getHours();
							if(hours==0 ){//从23点起 睡眠9个小时 到第二天8点 
								break;
							}
							
							
							boolean bo=true;
							for(WeiboSendBean weibo:weibolist){
								if(WeiboException.isLoginException()|| WeiboException.isShareException()){
									log.error("微博出异常："+WeiboException.toInfo());
									return ;
								}
								if("off".equals(weiboRuleBean.getIsswitch())){
									break;
								}
								Date nowdate=new Date();
								long datetime=nowdate.getTime();
								if(weibo.getSendDataList()!=null && weibo.getSendDataList().size()>0){
									Iterator<SendDataInfo> iterator= weibo.getSendDataList().iterator();
									while(iterator.hasNext()){
										if("off".equals(weiboRuleBean.getIsswitch())){
											log.info("监控到《"+gatherbean.getTitle()+"》的状态为OFF，临时退出");
											break;
										}
										
										SendDataInfo sdi=iterator.next();
										if(datetime>=sdi.getDatetime()){
											//   发送微博
											weiboService.sendWeibo(weibo, sdi, gatherbean);
											//无论发送成功与否都要删除
											iterator.remove();
										}else{
											break;
										}
									}
								}
								if(weibo.getSendDataList().size()>0){
									bo=false;
								}
							}
							//全部发送完后，跳出死循环
							if(bo){
								break;
							}
							//等待20秒 检查一次
							try {
//								log.info("《"+gatherbean.getTitle()+"》执行检查完毕，睡眠60秒");
								Thread.sleep(1000*60);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}
				log.info("《"+gatherbean.getTitle()+"》的状态为on,执行完毕睡眠"+weiboRuleBean.getRandomAll()+"分钟");
			}else{
//				log.info("《"+gatherbean.getTitle()+"》的状态为off,按设定时间睡眠"+weiboRuleBean.getRandomAll()+"分钟");
			}
			
			//按设定时间睡眠
			try {
				Thread.sleep(1000*60*weiboRuleBean.getRandomAll());
				
				try {
					Date d = new Date();
					int hours = d.getHours();
					if(hours==0 ){//从23点起 睡眠9个小时 到第二天8点 
						log.info("《"+gatherbean.getTitle()+"》进入夜间睡眠,随眠为9个小时，到第二天8点醒来");
						ShareManager.toInfo();
						Thread.sleep(1000*60*60*8);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
    }
	/**
	 * //计算本线程要发送哪些微博用户
	 * @param weiboRuleBean
	 * @return
	 */
	private List<WeiboSendBean> calculateSendUser(WeiboRuleBean weiboRuleBean){
		//组装微博用户
		String []userarray=weiboRuleBean.getUserArray();
		List<WeiboSendBean> weibolist=new ArrayList<WeiboSendBean>();
		for(String user:userarray){
			AccessInfo token=AccessToken.accessMap.get(user);
			if(token!=null){
				WeiboSendBean weiboSendBean=new WeiboSendBean();
				weiboSendBean.setAccessInfo(token);
//				weiboSendBean.setAccessToken(token);
//				weiboSendBean.setScreenName(user);
				weibolist.add(weiboSendBean);
			}
		}
		return weibolist;
	}
	
	
	
	/**
	 * for(i…20条内容发布){
		for(10个微博账号)
			微博账号list.add(内容发布)
			i++;
			if(i>20)break;
	 * @param weiboRuleBean
	 * @param sendDataList
	 */
	private void executeDifferent(List<WeiboSendBean> weibolist ,int []randomarray,List<SendDataInfo> sendDataList){
		//发布微博数
//		for(int i=0;i<sendDataList.size();i++){
//			for(WeiboSendBean wsb:weibolist){
//				if(i<sendDataList.size()){
//					SendDataInfo sdi=sendDataList.get(i);
////					this.setweibonick(sdi);
//					wsb.getSendDataList().add(sdi);
//					++i;
//				}else{
//					break;
//				}
//			}
//		}
		
		int i=0;
		while(i<sendDataList.size()){
			for(WeiboSendBean wsb:weibolist){
				if(i<sendDataList.size()){
					SendDataInfo sdi=sendDataList.get(i);
					wsb.getSendDataList().add(sdi);
					++i;
				}
			}
		}
		
	}
	/**
	 * 20条内容发布，每条内容设定睡眠时间，
		10个微博账号 *20个时间 升序排序
		List<List<bean>> accountList
		for(10个微博账号)
			List<bean> list
		for(20条内容发布){
				list.add(bean);
			accountList.add(list);

	 * @param weibolist
	 * @param randomarray
	 * @param sendDataList
	 */
	private void executeSame(List<WeiboSendBean> weibolist ,int []randomarray,List<SendDataInfo> sendDataList){
		for(WeiboSendBean wsb:weibolist){
			for(SendDataInfo senddatainfo:sendDataList){
				SendDataInfo newsenddata=new SendDataInfo();
				newsenddata.setContent(senddatainfo.getContent());
				newsenddata.setImageurl(senddatainfo.getImageurl());
				newsenddata.setOnlyid(senddatainfo.getOnlyid());
				newsenddata.setUrl(senddatainfo.getUrl());
//				this.setweibonick(newsenddata);
				wsb.getSendDataList().add(newsenddata);
			}
		}
	}
	
	
	
	
	
	
	public  int getRandom(int max) {
		return new Random().nextInt(max);
	}
	public  int getRandom(int min, int max) {
		int r = getRandom(max - min);
		return r + min;
	}

}
